package com.aiju.cash.ui.stockupdate.activity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.view.WindowManager;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.cash.R;
import com.aiju.cash.core.api.StockApi;
import com.aiju.cash.ui.main.BlotterSelectActivity;
import com.aiju.cash.ui.main.view.CharacterParser;
import com.aiju.cash.ui.stockupdate.History;
import com.aiju.cash.ui.stockupdate.adapter.StockAdapter;
import com.aiju.cash.ui.stockupdate.bean.Stock;
import com.aiju.cash.ui.stockupdate.widget.CustomClearAndSearechEdittext;
import com.aiju.common.event.EventBusHandler;
import com.aiju.common.event.EventCenter;
import com.aiju.support.recyclerView.DividerItemDecoration;
import com.aiju.utils.StringUtil;
import com.aiju.utils.T;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.timehop.stickyheadersrecyclerview.StickyRecyclerHeadersDecoration;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: 流冥
 * @date: 2017-6-30
 * @Description: 库存清单
 */

public class StockListActivity extends BaseTitleActivity implements StockAdapter.StockListItemClickListener, CustomClearAndSearechEdittext.OnClickSearchListener {
    String keyword;
    CustomClearAndSearechEdittext edittext;
    private View empty;
    private RecyclerView recyclerviewTeams;
    private LinearLayoutManager mTeamsLayoutManager;
    private StockAdapter adapter;
    StockApi stockApi;
    List<Stock.GoodsListBean> originList = new ArrayList<>();
    List<Stock.GoodsListBean> filterDateList = new ArrayList<>();
    private SharedPreferences mSharePreference;
    Gson gson;
    private static final String PRE_SEARCH_HISTORY = "pre_search_history";
    private static final String SEARCH_HISTORY = "search_history";
    /**
     * 汉字转换成拼音的类
     */
    private CharacterParser characterParser;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_stock_list);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        getContentData();
        initView();
        setViewValue();
        EventCenter.bindContainerAndHandler(getLifecycle(), new EventBusHandler() {
            public void onEventMainThread(Stock.GoodsListBean event) {
                notiyList(event);
            }
        });
    }

    void getContentData() {
        if (getIntent() != null) {
            keyword = getIntent().getStringExtra("keyword");
        }
    }


    void setViewValue() {
        edittext.setText(keyword);
        edittext.setSelection(edittext.getText().length());
    }

    void initView() {
        setCenterTitle("库存清单");
        empty = findViewById(R.id.iv_empty);
        mSharePreference = getSharedPreferences(PRE_SEARCH_HISTORY, 0);
        gson = new Gson();
        //实例化汉字转拼音类
        characterParser = CharacterParser.getInstance();
        recyclerviewTeams = (RecyclerView) findViewById(R.id.recyclerview_member);
        edittext = (CustomClearAndSearechEdittext) findViewById(R.id.search_bar);
        edittext.setOnClickSearchListener(this);
        mTeamsLayoutManager = new LinearLayoutManager(this);
        recyclerviewTeams.setLayoutManager(mTeamsLayoutManager);
        recyclerviewTeams.addItemDecoration(new DividerItemDecoration(this,
                DividerItemDecoration.VERTICAL_LIST));
        mAiJuTitleBarView.setRightOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(BlotterSelectActivity.class);
            }
        });
        mAiJuTitleBarView.setLeftOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(StockListActivity.this, StockListHomePageActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                startActivity(intent);
            }
        });
        showList(originList);
        stockApi = new StockApi(null);
        getList();
    }


    public void getList() {
        stockApi.getShopList(new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                stockApi.setDialogHelper(null);
                if (jsonData.isSuccess()) {
                    if (StringUtil.isBlank(data) || "[]".equals(data.toString())) {
                        empty.setVisibility(View.VISIBLE);
                        recyclerviewTeams.setVisibility(View.GONE);
                        return;
                    }
                    List<Stock> list = new Gson().fromJson(data, new TypeToken<List<Stock>>() {
                    }.getType());
                    if (list.size() == 0 || (list.size() == 1 && list.get(0).getGoodsList().size() == 0)) {
                        recyclerviewTeams.setVisibility(View.GONE);
                        empty.setVisibility(View.VISIBLE);
                    } else {
                        recyclerviewTeams.setVisibility(View.VISIBLE);
                        empty.setVisibility(View.GONE);
                    }
                    originList = setStockList(trans(list));
                    filterData(keyword);
                } else {
                    T.ToastShort(jsonData.getMsg());
                }

            }
        });
    }

    void showList(List<Stock.GoodsListBean> list) {

        if (adapter == null) {
            adapter = new StockAdapter(list);
            recyclerviewTeams.setAdapter(adapter);
            final StickyRecyclerHeadersDecoration headersDecor = new StickyRecyclerHeadersDecoration(adapter);
            recyclerviewTeams.addItemDecoration(headersDecor);
            adapter.setListener(this);
        } else {
            adapter.notifyDataSetChanged();
        }

    }

    @Override
    public void onItemClickListener(Stock.GoodsListBean goodsListBean) {
        Intent intent = new Intent(this, StockInfoActivity.class);
        intent.putExtra("goodsListBean", goodsListBean);
        startActivity(intent);
    }


    /**
     * 根据输入框中的值来过滤数据并更新ListView
     *
     * @param filterStr
     */
    private void filterData(String filterStr) {
        keyword=filterStr;
        filterDateList = new ArrayList<>();
        if (TextUtils.isEmpty(filterStr)) {
            filterDateList = originList;
        } else {
            for (Stock.GoodsListBean sortModel : originList) {
                String name = sortModel.getName();
                String code = sortModel.getCode();
                if (name.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1 ||
                        code.toUpperCase().indexOf(filterStr.toString().toUpperCase()) != -1
                        || characterParser.getSelling(name).toUpperCase().
                        startsWith(filterStr.toString().toUpperCase())
                        || characterParser.getSelling(code).toUpperCase().
                        startsWith(filterStr.toString().toUpperCase())) {
                    filterDateList.add(sortModel);
                }
            }
        }
        if (filterDateList.size() == 0) {
            recyclerviewTeams.setVisibility(View.GONE);
            empty.setVisibility(View.VISIBLE);
        } else {
            adapter.setList(filterDateList, keyword);
            recyclerviewTeams.setVisibility(View.VISIBLE);
            empty.setVisibility(View.GONE);
        }
    }


    public List<Stock.GoodsListBean> setStockList(List<Stock> d) {
        List<Stock.GoodsListBean> list = new ArrayList<>();
        for (Stock b : d) {
            list.addAll(b.getGoodsList());
        }
        return list;
    }


    @Override
    public void onClickSearch(String value) {
        if (!StringUtil.isBlank(value)) {
            save(value);
        }
        filterData(value);
    }


    public void notiyList(Stock.GoodsListBean bean) {
        for (int i = 0; i < originList.size(); i++) {
            if (originList.get(i).getId() == bean.getId()) {
                originList.get(i).setSurplus(bean.getSurplus());
                originList.get(i).setInventory(bean.getInventory());
                break;
            }
        }
        adapter.notifyDataSetChanged();
    }

    //保存搜索内容到本地
    public void save(String text) {
        List<History> list = new ArrayList<>();
        List<History> oldList = new ArrayList<>();

        list.add(new History(text));

        String oldText = mSharePreference.getString(SEARCH_HISTORY, "");
        if (!StringUtil.isBlank(oldText)) {
            oldList = gson.fromJson(oldText, new TypeToken<List<History>>() {
            }.getType());
        }
        SharedPreferences.Editor myEditor = mSharePreference.edit();
        for (int i = 0; i < oldList.size(); i++) {
            if (text.equals(oldList.get(i).getName())) {
                oldList.remove(i);
                break;
            }
        }
        list.addAll(oldList);
        myEditor.putString(SEARCH_HISTORY, gson.toJson(handlerHistoryList(list)));
        myEditor.commit();
    }

    List<History> handlerHistoryList(List<History> list) {

        if (list.size() <= 6) {
            return list;
        } else {
            return list.subList(0, 6);
        }

    }

    private List<Stock> trans(List<Stock> list) {
        for (int i = 0; i < list.size(); i++) {
            List<Stock.GoodsListBean> goodsList = list.get(i).getGoodsList();
            for (int j = 0; j < goodsList.size(); j++) {
                goodsList.get(j).setGoodsTypeName(list.get(i).getName());
            }
        }
        return list;
    }
}
